package com.tuanbiao.ui.auth;

import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.PopupWindow;

import androidx.appcompat.widget.AppCompatButton;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.abiao.lib_utils.ViewUtils;
import com.hjq.toast.ToastUtils;
import com.hzjq.data.entity.UIDRule;
import com.hzjq.data.hzjq.entity.CapRecordEntity;
import com.hzjq.data.minbao.entity.AuthEntity;
import com.hzjq.lib.BlastKool;
import com.hzjq.lib.bean.PlanInfo;
import com.hzjq.lib.cap.bean.ScanResult;
import com.tuanbiao.R;
import com.tuanbiao.base.mvp.BasePresenterActivity;
import com.tuanbiao.controllers.AuthController;
import com.tuanbiao.databinding.ActivityAuthOffLineBinding;
import com.tuanbiao.dialog.BaseDialogFragment;
import com.tuanbiao.dialog.InsertDetonatorDialog;
import com.tuanbiao.dialog.InsertDetonatorStartEndDialog;
import com.tuanbiao.dialog.MenuDialog;
import com.tuanbiao.dialog.MessageDialog;
import com.tuanbiao.models.AuthModel;
import com.tuanbiao.presenter.auth.AuthOfflinePresenter;
import com.tuanbiao.ui.auth.adapter.AuthOfflineAdapter;
import com.tuanbiao.utils.ClickUtil;
import com.tuanbiao.utils.LibCollections;
import com.tuanbiao.utils.MediaUtils;

import java.util.Collections;
import java.util.List;
import java.util.Objects;

import timber.log.Timber;

public class AuthOfflineActivity extends BasePresenterActivity<AuthOfflinePresenter, ActivityAuthOffLineBinding> implements AuthController.OfflineView {
    private AuthOfflineAdapter authOfflineAdapter;

    public static void start(Context context) {
        Intent starter = new Intent(context, AuthOfflineActivity.class);
        context.startActivity(starter);
    }

    @Override
    protected ActivityAuthOffLineBinding getBindingView() {
        return ActivityAuthOffLineBinding.inflate(getLayoutInflater());
    }

    @Override
    protected void initView() {
        refreshDetonatorCount();
        binding.ivToolbarBack.setOnClickListener(getBackListener());
        binding.btnDownloadWorkCode.setOnClickListener(view -> {
            if (ClickUtil.isFastClick()) {
                return;
            }
            if (LibCollections.isEmpty(authOfflineAdapter.getData())) {
                showMessage("暂无雷管需要授权");
                return;
            }
            mPresenter.downloadAuthFile(authOfflineAdapter.getData());
        });
        binding.ivMore.setOnClickListener(v -> {
            if (ClickUtil.isFastClick()) {
                return;
            }
            showRightMenu();
        });
        authOfflineAdapter = new AuthOfflineAdapter();
        authOfflineAdapter.addChildClickViewIds(R.id.iv_delete);
        authOfflineAdapter.setOnItemChildClickListener((adapter, view, position) -> {
            AuthEntity.Lgs.Lg lg = (AuthEntity.Lgs.Lg) adapter.getItem(position);
            showDeleteDialog(lg);
        });
        authOfflineAdapter.setEmptyView(ViewUtils.layoutId2View(R.layout.include_no_data));
        binding.rvContent.setLayoutManager(new LinearLayoutManager(getActivity()));
        binding.rvContent.setAdapter(authOfflineAdapter);
    }

    private void showRightMenu() {
        View rootView = LayoutInflater.from(getActivity()).inflate(R.layout.pop_menu_detonator_auth, null);
        //我这里给的是固定高度  固定高度需要在外边设置  在布局中设置外边不设置是没有效果的
        final PopupWindow window = new PopupWindow(rootView, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, true);
        window.setBackgroundDrawable(new BitmapDrawable());
        // 设置弹窗外可点击
        window.setOutsideTouchable(true);
        //获取自身的长宽高
        rootView.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
        //获取需要在其上方显示的控件的位置信息
        int[] locations = new int[2];
        binding.ivMore.getLocationOnScreen(locations);
        window.showAsDropDown(binding.ivMore);
        window.setFocusable(true);
        window.update();


        AppCompatButton btnOnlineInput = (AppCompatButton) rootView.findViewById(R.id.btn_online_input);
        AppCompatButton btnInsert = (AppCompatButton) rootView.findViewById(R.id.btn_insert);
        AppCompatButton btnInsertBatch = (AppCompatButton) rootView.findViewById(R.id.btn_insert_batch);
        AppCompatButton btnSort = (AppCompatButton) rootView.findViewById(R.id.btn_sort);
        AppCompatButton btnPlanClear = (AppCompatButton) rootView.findViewById(R.id.btn_plan_clear);

        btnInsertBatch.setOnClickListener(v -> {
            if (ClickUtil.isFastClick()) {
                return;
            }
            window.dismiss();
            showInsertBatchDialog();
        });
        btnInsert.setOnClickListener(v -> {
            if (ClickUtil.isFastClick()) {
                return;
            }
            window.dismiss();
            showInsertDialog();
        });

        btnOnlineInput.setOnClickListener(v -> {
            if (ClickUtil.isFastClick()) {
                return;
            }
            mPresenter.menuReadOnline(LibCollections.size(authOfflineAdapter.getData()));
            window.dismiss();
        });
        btnSort.setOnClickListener(v -> {
            window.dismiss();
            showSortDialog();
        });
        btnPlanClear.setOnClickListener(v -> {
            window.dismiss();
            showClearDialog();
        });
    }

    private void showInsertBatchDialog() {
        InsertDetonatorStartEndDialog.newInstance().setListener(new InsertDetonatorStartEndDialog.OnConfirmListener() {
            @Override
            public void onConfirm(BaseDialogFragment dialogFragment, String start, String end) {
                mPresenter.menuInsertDetonator(start, end);
            }

            @Override
            public void onCancel() {

            }
        }).showNow(getSupportFragmentManager(), "InsertDetonatorStartEndDialog");
    }

    private void showDeleteDialog(AuthEntity.Lgs.Lg entity) {
        new MessageDialog.Builder(getActivity())
                .setTitle("警告")
                .setMessage("是否删除当前雷管数据")
                .setListener(dialog -> {
                    authOfflineAdapter.remove(entity);
                    refreshDetonatorCount();
                }).show();
    }

    private void showDeleteDialog() {
        new MessageDialog.Builder(getActivity())
                .setTitle("警告")
                .setMessage("是否删除所选雷管数据")
                .setListener(dialog -> {
                    authOfflineAdapter.removeSelected();
                }).show();
    }

    private void showClearDialog() {
        new MessageDialog.Builder(getActivity())
                .setTitle("警告")
                .setMessage("是否删除所有雷管数据")
                .setListener(dialog -> {
                    authOfflineAdapter.setNewInstance(null);
                    refreshDetonatorCount();
                }).show();
    }

    private void showSortDialog() {
        new MenuDialog.Builder(getActivity())
                .setList("正序", "倒序")
                .setListener((MenuDialog.OnListener<String>) (dialog, position, item) -> {
                    Collections.sort(authOfflineAdapter.getData(), (o1, o2) -> {
                        if (0 == position) {
                            return Objects.requireNonNull(o1.getUid()).compareTo(Objects.requireNonNull(o2.getUid()));
                        } else {
                            return Objects.requireNonNull(o2.getUid()).compareTo(Objects.requireNonNull(o1.getUid()));
                        }
                    });
                    authOfflineAdapter.notifyDataSetChanged();
                }).show();
    }

    private void showInsertDialog() {
        InsertDetonatorDialog.newInstance(0)
                .setListener(new InsertDetonatorDialog.OnConfirmListener() {
                    @Override
                    public void onConfirm(BaseDialogFragment dialogFragment, String uid, String delay, String row, String column, UIDRule rule) {
                        if(rule == UIDRule.QH214){
                            CapRecordEntity entity = new CapRecordEntity();
                            entity.setConvertUid(uid);
                            String duid = BlastKool.Companion.getCapUidConvertor().restore(entity);
                            entity.setUid(duid);
                            uid = BlastKool.Companion.getCapUidConvertor().convert(entity);
                        }
                        if(uid.isEmpty()){
                            ToastUtils.show("UID不正确");
                            return;
                        }
                        mPresenter.menuInsertDetonator(uid);
                    }

                    @Override
                    public void onCancel() {

                    }
                })
                .show(getSupportFragmentManager(), "InsertDetonatorDialog");
    }


    @Override
    protected AuthOfflinePresenter createPresenter() {
        return new AuthOfflinePresenter(new AuthModel(), this);
    }


    @Override
    public void setItems(List<AuthEntity.Lgs.Lg> lgs) {
        authOfflineAdapter.setNewInstance(lgs);
    }

    @Override
    public void showRepeatDialog(int repeatCount) {

    }

    @Override
    public void addDetonators(List<AuthEntity.Lgs.Lg> newCaps) {
        for (AuthEntity.Lgs.Lg lg : newCaps) {
            if (!authOfflineAdapter.contains(lg)) {
                authOfflineAdapter.addData(lg);
            }
        }
        MediaUtils.playSound(R.raw.sound);
        refreshDetonatorCount();
    }

    @Override
    public void addDetonators(AuthEntity.Lgs.Lg newCaps) {
        if (authOfflineAdapter.contains(newCaps)) {
            MediaUtils.playSound(R.raw.repeat_scan);
        } else {
            MediaUtils.playSound(R.raw.sound);
            authOfflineAdapter.addData(newCaps);
        }
        refreshDetonatorCount();
    }

    @Override
    public void showUidError(long uidErrorCount) {
        binding.tvDetonatorCount.setText(getString(R.string.detonator_register_statistics_detonator_count, uidErrorCount));
    }

    @Override
    public void showStatistics(PlanInfo planInfo) {

    }

    @Override
    public void showScanRepeat(Object o, ScanResult scanResult) {

    }

    @Override
    public void onScannerTypeChange(boolean isScanner) {
        binding.tvToolbarSubTitle.setText(isScanner ? R.string.detonator_register_sub_title_scan : R.string.detonator_register_sub_title_foot_line);
    }

    @Override
    public void scrollToPosition(String uid) {
        int position = authOfflineAdapter.getPosition(uid);
        binding.rvContent.scrollToPosition(position);
//        authOfflineAdapter.toggleSelect(position);
    }

    private void refreshDetonatorCount() {
        int count = 0;
        if (null != authOfflineAdapter) {
            count = LibCollections.size(authOfflineAdapter.getData());
        }
        Timber.i("refreshDetonatorCount"+count);
        binding.tvDetonatorCount.setText(getString(R.string.detonator_register_statistics_detonator_count, count));
        if (0 == count && null != authOfflineAdapter) {
            authOfflineAdapter.setEmptyView(ViewUtils.layoutId2View(R.layout.include_no_data));
        }

    }
}